import 'package:flutter/material.dart';

class AIChatScreen extends StatefulWidget {
  const AIChatScreen({super.key});

  @override
  State<AIChatScreen> createState() => _AIChatScreenState();
}

class _AIChatScreenState extends State<AIChatScreen> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  
  // 聊天消息列表
  final List<Map<String, dynamic>> _messages = [
    {
      'isUser': false,
      'message': '你好！我是你的AI学习助手。有什么我可以帮助你的吗？',
      'timestamp': DateTime.now().subtract(const Duration(minutes: 5)),
    },
  ];
  
  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }
  
  void _sendMessage() async {
    final message = _messageController.text.trim();
    if (message.isEmpty) return;
    
    // 添加用户消息
    setState(() {
      _messages.add({
        'isUser': true,
        'message': message,
        'timestamp': DateTime.now(),
      });
      _isLoading = true;
    });
    
    _messageController.clear();
    _scrollToBottom();
    
    // 模拟AI响应
    await Future.delayed(const Duration(seconds: 1));
    
    String aiResponse = '';
    
    // 根据用户输入生成简单的响应
    if (message.contains('你好') || message.contains('嗨') || message.contains('hi')) {
      aiResponse = '你好！很高兴和你聊天。我可以帮你解答学习上的问题，或者提供学习建议。';
    } else if (message.contains('学习方法') || message.contains('如何学习')) {
      aiResponse = '高效学习的方法包括：\n1. 制定明确的学习计划\n2. 使用番茄工作法提高专注度\n3. 定期复习巩固知识\n4. 多做练习题加深理解\n5. 保持充足的睡眠和适当的运动';
    } else if (message.contains('英语') || message.contains('单词')) {
      aiResponse = '学习英语的建议：\n1. 每天坚持背诵单词\n2. 多听英语音频提高听力\n3. 尝试用英语思考和表达\n4. 阅读英语原版材料\n5. 找机会进行英语口语练习';
    } else if (message.contains('数学') || message.contains('公式')) {
      aiResponse = '学习数学的建议：\n1. 理解概念比记忆公式更重要\n2. 多做练习题巩固知识\n3. 尝试用不同方法解决同一问题\n4. 建立知识体系，理解知识间的联系\n5. 遇到难题时，可以分解成小问题逐步解决';
    } else if (message.contains('谢谢') || message.contains('感谢')) {
      aiResponse = '不客气！如果还有其他问题，随时可以问我。';
    } else {
      aiResponse = '这是个很好的问题。作为学习助手，我建议你可以尝试分解问题，逐步理解。如果有具体的学科问题，可以告诉我，我会尽力提供帮助。';
    }
    
    // 添加AI响应
    setState(() {
      _messages.add({
        'isUser': false,
        'message': aiResponse,
        'timestamp': DateTime.now(),
      });
      _isLoading = false;
    });
    
    _scrollToBottom();
  }
  
  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AI学习助手'),
        centerTitle: true,
      ),
      body: Column(
        children: [
          // 聊天消息列表
          Expanded(
            child: ListView.builder(
              controller: _scrollController,
              padding: const EdgeInsets.all(16),
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                final message = _messages[index];
                final isUser = message['isUser'] as bool;
                
                return Padding(
                  padding: const EdgeInsets.only(bottom: 16),
                  child: Row(
                    mainAxisAlignment: isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (!isUser) ...[  
                        CircleAvatar(
                          backgroundColor: Colors.blue.shade100,
                          child: const Icon(Icons.assistant, color: Colors.blue),
                        ),
                        const SizedBox(width: 8),
                      ],
                      
                      Flexible(
                        child: Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: isUser ? Colors.blue : Colors.grey.shade200,
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                message['message'] as String,
                                style: TextStyle(
                                  color: isUser ? Colors.white : Colors.black,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                _formatTime(message['timestamp'] as DateTime),
                                style: TextStyle(
                                  fontSize: 12,
                                  color: isUser ? Colors.white70 : Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      
                      if (isUser) ...[  
                        const SizedBox(width: 8),
                        CircleAvatar(
                          backgroundColor: Colors.blue,
                          child: const Icon(Icons.person, color: Colors.white),
                        ),
                      ],
                    ],
                  ),
                );
              },
            ),
          ),
          
          // 正在输入指示器
          if (_isLoading)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Row(
                children: [
                  CircleAvatar(
                    backgroundColor: Colors.blue.shade100,
                    radius: 16,
                    child: const Icon(Icons.assistant, color: Colors.blue, size: 16),
                  ),
                  const SizedBox(width: 8),
                  const Text('AI正在思考...'),
                  const SizedBox(width: 8),
                  const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
                ],
              ),
            ),
          
          // 输入区域
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.grey.withOpacity(0.2),
                  spreadRadius: 1,
                  blurRadius: 3,
                  offset: const Offset(0, -1),
                ),
              ],
            ),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _messageController,
                    decoration: const InputDecoration(
                      hintText: '输入你的问题...',
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    ),
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => _sendMessage(),
                  ),
                ),
                const SizedBox(width: 8),
                IconButton(
                  onPressed: _sendMessage,
                  icon: const Icon(Icons.send),
                  color: Colors.blue,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  String _formatTime(DateTime dateTime) {
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}